/*
 * @(#)IndexTag.java $version 2010. 8. 11
 *
 * Copyright 2007-2010 NHN Corp. All rights Reserved. 
 * NHN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.nhncorp.usf.web.taglibs.pager;

import java.text.MessageFormat;

import javax.servlet.jsp.JspWriter;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.nhncorp.usf.core.config.PagerConfigInfo;
import com.nhncorp.usf.core.config.PagerConfigInfos;
import com.nhncorp.usf.core.result.template.directive.PagerInfo;

/**
 * 선택된 색인 위치로 이동하기 위한 {@link PagerTag}.
 *
 * @author Web Platform Development Team
 */
public class IndexTag extends PagerTag {
	static final long serialVersionUID = -5645046274470034054L;
	static Log log = LogFactory.getLog(IndexTag.class);

	public IndexTag() {
	}

	public IndexTag(String appendings) {
		super(appendings);
	}

	/**
	 * {@inheritDoc}
	 * */
	protected void generate(NavigatorTag parent, PagerInfo pagerInfo) throws Exception {
		PagerConfigInfo pagerConfig = PagerConfigInfos.get(parent.pagerType);
		
		if (parent.index.length > 0 && pagerConfig == null) {
			throw new IllegalArgumentException("failed to find pager config for type '" + parent.pagerType + "'");
		}
		
		if (pagerConfig != null) {
			JspWriter out = pageContext.getOut();
			String queryString = getQueryString(pagerInfo);

			for (int i = 0; i < parent.index.length; i++) {
				if (i > 0) {
					out.print(pagerConfig.getSeperator());
				}

				String endATag = END_ATAG;

				boolean current = parent.page == parent.index[i];
				String atagAttribute = current ? pagerConfig.getCurrentAtagAttribute()
					: pagerConfig.getIndexAtagAttribute();
				String messageIndex = current ? pagerConfig.getCurrent() : pagerConfig.getIndex();

				String message = resolve(messageIndex, pagerConfig.getDataHandlerName());
				String startTag = getStartTag(parent, queryString, parent.index[i], atagAttribute);
				String formatted = MessageFormat.format(message, startTag, parent.index[i], endATag);
				out.print(formatted);

				out.println();
			}
		}
	}

	/**
	 * {@inheritDoc}
	 * */
	protected void failed(Exception ex) {
		log.error(ex);
	}
}
